<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <!--设置页面基础路径 ：上下文路径+/
        /logistics/
        以后也没按的所有的请求跳转都不要手动加上最前面的斜杠，自动根据上下文路径进行跳转
        服务器根路径/logistics/admin/insert
    -->
    <base th:href="${#request.getContextPath()}+'/'">

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" th:href="@{/lib/bootstrap-3.3.7/css/bootstrap.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css}"/>
    <style type="text/css">

        /*設置jquery.validate错误字体颜色*/
        label.error { color: red; }
    </style>
</head>
<body>
<div class="container" style="margin-top: 20px">
    <div class="row">
        <div class="col-md-6">
            <form class="form form-horizontal" method="post" th:action="@{{path}(path=${role eq null ? 'role/insert' : 'role/update'})} "  id="roleForm">
                <!--隐藏域：角色id-->
                <input name="roleId" type="hidden" th:value="${role?.roleId}">
                <!--隐藏域：权限id，多个权限使用逗号隔开-->
                <input name="permissionIds" id="permissionIds" type="hidden" >

                <div class="form-group">
                    <label for="rolename" class="col-sm-3 control-label"><span class="c-red">*</span>角色名称：</label>
                    <div class="col-sm-9">
                        <input type="text"class="form-control"   th:value="${role?.rolename}" placeholder="请输入角色名称" id="rolename" name="rolename">
                    </div>
                </div>
                <div class="form-group">
                    <label for="remark" class="col-sm-3 control-label">角色描述：</label>
                    <div class="col-sm-9">
                        <textarea id="remark" name="remark"  class="form-control" rows="3" placeholder="请输入角色描述"  th:text="${role?.remark}"></textarea>

                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </div>
            </form>

        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label >角色权限</label>
                <div>
                    <ul class="ztree" id="permissionTree"></ul>

                </div>
            </div>
        </div>
    </div>


</div>

<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" th:src="@{lib/jquery-1.11.3/jquery.js}"></script>
<script type="text/javascript" th:src="@{lib/bootstrap-3.3.7/js/bootstrap.js}"></script>
<script type="text/javascript" th:src="@{lib/zTree/v3/js/jquery.ztree.all-3.5.js}"></script>
<script type="text/javascript" th:src="@{lib/layer/2.4/layer.js}"></script>
<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" th:src="@{lib/jquery.validation/1.14.0/jquery.validate.js}"></script>
<script type="text/javascript" th:src="@{lib/jquery.validation/1.14.0/validate-methods.js}"></script>
<script type="text/javascript" th:src="@{lib/jquery.validation/1.14.0/messages_zh.js}"></script>
<script>
    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "permissionId",
                pIdKey: "parentId",
            },
            key: {
                name: "pname"
            }
        },
        async: {
            enable: true,
            type: "get",
            url: "permission/getAllPermission",
            dataFilter: ajaxDataFilter
        },
        callback: {
            /*异步加载成功以后的回调*/
            onAsyncSuccess: zTreeOnAsyncSuccess
        }
    }
    /*异步加载成功以后的回调*/
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
      /**
       * 回显思路
       * 1.获取树对象
       * 2.通过树的属性值获取对象的节点对象
       *  通过后台共享的权限id的值获取对应节点
       * 3.让其选中即可
       * */
      var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
      /*获取后台共享的权限id*/
      var permissionIds = '[[${permissionIds}]]';
      var permissionIdsArr = permissionIds.split(",");
      console.log(permissionIds,permissionIdsArr);
      //循环数组
      $.each(permissionIdsArr,function(index,permissionId){
          //通过树的属性值获取对象的节点对象,通过后台共享的权限id的值获取对应节点
          var node = treeObj.getNodeByParam("permissionId", permissionId);
          console.log(permissionId,node);
          //让其选中
          treeObj.checkNode(node, true, false);
      });

    };

    /*预处理zTree数据函数*/
    function ajaxDataFilter(treeId, parentNode, responseData) {
        if (responseData) {
            for(var i =0; i < responseData.length; i++) {
                responseData[i].open =true;
            }
        }
        return responseData;
    };


    //3.初始化ztree
    $(function(){

        $.fn.zTree.init($("#permissionTree"), setting);

    });

</script>

<script type="text/javascript">
    $(function(){
        /*使用Jquery.validate进行表单校验*/
        $("#roleForm").validate({
            /*校验规则*/
            rules:{
                rolename:{
                    required:true,
                }

            },
            /*校验失败的提示消息*/
            messages:{
                rolename:{
                    required:"角色名称不能为空",
                }
            },
            /*校验成功以后出发的函数
            * form ：当前表单（DOM对象）
            * */
            submitHandler:function(form){

                //获取树对象
                var treeObj = $.fn.zTree.getZTreeObj("permissionTree");
                //获取选中的节点
                var nodes = treeObj.getCheckedNodes(true);

                if(nodes.length == 0){
                    layer.msg("此角色还未分配权限",{icon:0});
                    return false;
                }

                //声明数组，用于添加权限id
                var permissionIds = [];
                //循环节点
                $.each(nodes,function(index,node){
                    //将选中的节点的权限id添加到数组
                    permissionIds.push(node.permissionId);
                });

                //将获取权限id设置给表单隐 藏域 id=permissionIds的value
                $("#permissionIds").val(permissionIds.toString());

                console.log(permissionIds);


                //获取表单的提交地址
                var url = $(form).attr("action");
                console.log(url);

                /*序列化表单数据*/
                var formData = $(form).serialize();
                console.log(formData);

                /*使用ajax提交表单*/
                $.post(url,formData,function(data){
                    layer.msg(data.msg,{icon:data.code},function(){

                        //操作数据成功
                        if(data.code == 1){
                            //先刷新父页面表格（当前页面是adminManager页面弹出来的子页面，所以刷新父页面）
                            parent.refreshTable();
                            //父页面adminManager关闭弹出子页面
                            parent.layer.closeAll();
                        }

                    });
                });

            }
        })
    })
</script>
<!--/请在上方写此页面业务相关的脚本-->
</body>
</html>
